<?php
/************************************************************/
/*				Class Mere controller 						*/
/************************************************************/
//Chaque classes de controle doit hériter de cette classe

class Controller{

	var $vars = array();
	var $layout = 'default';

	public function set($d){
		$this->vars = array_merge($this->vars, $d);
	}

	//permet d'afficher la vue correspondant au controller dans lequel on se trouve
	public function render($filename){
		//envoies les données de $vars a la vu
		extract($this->vars);
		ob_start();
		$folder = str_replace('Controller', '',get_class($this));
		require(ROOT.'views/'.$folder.'/'.$filename.'.php');
		$content_for_layout = ob_get_clean();
		if($this->layout==false){
			echo $content_for_layout;
		}else{ require(ROOT.'views/layout/'.$this->layout.'.php');}
	}

	/*Charger un model*/
	function loadModel($name){
		require_once( ROOT. 'models/'.strtolower($name).'.php');
			$this->$name = new $name();
	}

	/*Verifie le format de chaque champs et si ils sont obligatoires*/
	public function checkrules($tab, $model){
		$valide = true;
		foreach($model->rules as $field=>$regles){
			list($fo, $obl) = explode(':', $regles);
				if(isset($tab[$field]) && $tab[$field] != ""){
					if(!preg_match($fo, $tab[$field])){
						$valide = false;
					}
				}
				if($obl == '*' && (!isset($tab[$field]) || $tab[$field] =='')){
					$valide = false;
				}
		}
		return $valide;
	}

	/*Retoure les champs invalides*/
	public function getInvalidFields($tab, $model){
		$invFields = '';
		foreach($model->rules as $field=>$regles){
			list($fo, $obl) = explode(':', $regles);
				/*format des champs*/
				if(isset($tab[$field]) && $tab[$field] != ""){
					if(!preg_match($fo, $tab[$field])){
						$invFields[$field] = 'format:'.$field;
					}
				}
				/*Champs obligatoires*/
				if($obl == '*' && (!isset($tab[$field]) || $tab[$field] =='')){
					$invFields[$field] = 'oblg:'.$field;
				}
		}
		return $invFields;
	}

	/*Verifie le format entré dans les champs de saisie*/
	public function checkFormat($tab, $model){
		$valide = true;
		foreach($model->rules as $field=>$regles){
			list($fo) = explode(':', $regles);
			 if(isset($tab[$field])){
				if(!preg_match($fo, $tab[$field])){
						$valide = false;
					}
				}
			}
			return $valide;
		}
	/*Place les variables POST dans un tableau associatif*/
	public function setPostToTable(){
		$tab = null;
		foreach ($this->inputPost as $value) {
			if(isset($_POST[$value]) && $_POST[$value] != ''){
				$tab[$value] = $_POST[$value];
			}
		}
		return $tab;
	}

}

?>